var module = require('./lib/module.Base');
$(document).ready(function($) {
    var HTML_template = {
        userData:   '<div class="col-25">' +
                    '<div class="head-pic"><img src="<%= _.isEmpty(userCustomType2)?\'/images/head-pic.png\':userCustomType2 %>"></div>' +
                    '</div>' +
                    '<div class="col-5">&nbsp;</div>' +
                    '<div class="col-35">' +
                    '<p class="margin0 c3 fs85"><%= realName %></p>' +
                    '<p class="margin0 c6 fs75">电话：<%= mobile %></p>' +
                    '<p class="margin0 c6 fs75">编号：<%= userId %></p>' +
                    '</div>' +
                    '<div class="col-25 tar"><span class="icon icon-right mt1" style="margin-right: .35rem;margin-top: 1.3rem;"></span></div>',
        userDataEdit:'<% _.forEach(data, function(item,key) { %><div class="content-padded fs75 <%if(!_.eq(key,0)){%>borderT pt5h<%}%>">' +
                    '<div class="row no-gutter">' +
                    '<div class="col-20">' +
                    '<p class="margin0 c6"><%= item.name %></p>' +
                    '</div>' +
                    '<div class="col-80">' +
                    '<p class="margin0 tar c3"><input name=<%= item.key %> type="text" value="<%= item.val %>" class="c3 tar border0 bgn wall" disabled="disabled" /></p>' +
                    '</div>' +
                    '</div>' +
                    '</div><% }); %>',
        userPic:'<img width="67" height="67" src="<%= _.isEmpty(userCustomType2)?\'/images/head-pic.png\':userCustomType2 %>"></div>">',
        yhqData:'<% _.forEach(data, function(item) { %><li><p class="margin0 c6 fs75"><span class="<%= item.isUsed?\'\':\'pink\' %>" style="font-size:2.15rem"><%= item.priceType %></span>元</p></li><% }); %>',
        yhqCount:'<a href="#tab1" class="tab-link active button">未使用（<%= type1 %>）</a><a href="#tab2" class="tab-link button">已使用（<%= type2 %>）</a>',
        colMenu:'<% _.forEach(data, function(item,key) { %><div class="borderB"><div class="content-padded fs75"><div class="row no-gutter"><div class="col-100"><a href="<%=item.href%>" class="c3 clear"><p class="margin0 clear fl"><i class="icon<%=item.icon%> fl"></i><span class="fs75 fl"><%=item.name%></span></p><span class="icon icon-right fr"></span></a></div></div></div></div><% })%>',
        recommendData:'<% _.forEach(data, function(item,key) { %><div class="order-box bgf mb5h"><div class="borderB"><div class="content-padded" style="margin: 0 .5rem;"><div class="row pt5h pb5h"><div class="col-100 c6 fs75"><span><%= item.recommendTime%></span><span class="ml5h">推荐人：<%= item.recommend%></span></div></div></div></div><div class="orderP-box borderB mt25h"><div class="fs75 borderB"><div class="content-padded"><div class="row no-gutter"><div class="col-50 c9"><p class="margin0 c3 fs75"><%= item.userName%></p></div><div class="col-50 c3 tar"><p class="margin0 c3 fs75"><%= item.userMobile%></p></div></div></div></div><div class="content-padded fs75"><div class="row" style="overflow: visible; min-height: 1.35rem"><div class="col-50">&nbsp;</div><div class="col-25 rel"><a href="javascript:void(0);" class="button button-fill h-null-btn-nob">更多</a><div class="shpiaof"><a href="/work/customer.html#addCustomer">新增客户</a><a href="javascript:void(0)" class="delRecommend" data-id=<%= item.id%>>删除推荐</a><a href="javascript:void(0);" class="border0 close-btn-menu">取消</a></div></div><div class="col-25"><a href="tel:<%= item.userMobile%>" class="button button-fill red-null-btn">联系他</a></div></div></div></div></div><% })%>',
        orderData:'<% _.forEach(data, function(item,key) { %><div class="order-box bgf mb5h"><input type="hidden" name="id" value="<%=item.id%>"><div class="content-padded" style="margin: 0 .5rem;"><div class="row pt5h pb5h"><div class="col-60 c9 fs65"><p class="margin0">订单编号<%=item.id%></p><p class="margin0">下单时间：<%=item.createTime%></p></div><div class="col-40 tar c3 fs65"><p class="margin0"><%=item.storeName%>（<%=item.drawerName%>）</p><p class="margin0"><%=item.drawerNumber%></p></div></div><div class="no-gutter borderT"><% _.forEach(item.products, function(product,key) { %><div class="row pt5h pb5h"><div class="col-50 c9"><p class="margin0 c3 fs75"><%=product.productName%></p></div><div class="col-10 c9 fs65 tar"><p class="margin0">x<%=product.quantity%></p></div><div class="col-40 c3 tar"><p class="margin0">￥<%=product.price2%>/<%=product.unit%></p></div></div><% })%></div><div class="fs75 borderT tar"><div class="content-padded clear"><p class="fs65 margin0 pb5h">合计：￥<span class="fs75"><%=item.totalAmount%></span><span class="tdl c9 ml5h">(运费：<%=item.postFee%>元)</span><span class="c9 fs65 ml1">| 省下<span><%=item.province%></span>元</span></p></div></div></div></div><% })%>',
        customersInfo:'<%if(userCustomType == \'STORE\'){%><div class="bgf borderB borderT mt5h"><div class="content-padded pt5h pb5h" style="margin: 0 .5rem"><p class="margin0 clear"><i class="icon1 fl"></i><span class="fs75 fl">省钱</span></p></div></div><div class="bgf mb5h "><div class="content-padded" style="margin: 0 .5rem"><div class="row no-gutter pt5h pb5h"><div class="col-50"><a href="#yhq"><div class="margin0 clear"><i class="icon2 fl"></i><div class="fl"><p class="margin0 clear"><span class="fs75 fl">优惠券</span><span class="yhq-num fs75 fl ml5h">20</span></p><p class="c6 fs75 margin0">￥45.00</p></div></div></a></div><div class="col-50"><div class="margin0 clear" style="border-left: 1px #e5e5e5 solid; padding-left: 1.5rem"><i class="icon3 fl"></i><div class="fl"><p class="margin0 clear"><span class="fs75 fl">共省钱</span></p><p class="c6 fs75 margin0">￥825.00</p></div></div></div></div></div></div><%}%>',
        sendList:'<% _.forEach(data, function(item,key) { %><div class="borderB"><div class="content-padded"><div class="row pb5h"><div class="col-50 fs75"><span class="c6"><%=item.giftName%></span></div><div class="col-50 tar"><p class="margin0 pink fs75">¥ <%=item.amount%>元</p></div></div><div class="row"><div class="col-50"><p class="margin0 c9 fs65">接收人：<%=item.storeName%></p></div><div class="col-50 tar"><p class="margin0 c9 fs65">发放时间： <%=item.recommendTime%></p></div></div></div></div><%})%>'

    };
    var formKeyName = [
        {data:{
        storeName:{name:"店铺名称",order:1},
        realName:{name:"店主姓名",order:2},
        mobile:{name:"联系电话",order:3},
        alternateMobile:{name:"备用电话",order:4},
        address:{name:"店铺地址",order:5}
        },userCustomType:['STORE','SELLER']},
        {data:{
            userId:{name:"编号",order:1},
            realName:{name:"姓名",order:2},
            mobile:{name:"电话",order:3},
            address:{name:"负责片区",order:4},
        },userCustomType:['AGENT','BUYER','CARRIER']}
    ];
    var menu = [
        {name:'被推荐客户',href:'#recommendCustomers',order:1,icon:9,userCustomType:['AGENT']},
        {name:'推荐的朋友',href:'#recommend',order:2,icon:4,userCustomType:['STORE','SELLER']},
        {name:'发放的优惠券',href:'#send',order:3,icon:11,userCustomType:['AGENT']},
        {name:'代下单',href:'#steadOrder',order:4,icon:10,userCustomType:[,'AGENT']},
        {name:'修改密码',href:'#changePW2',order:5,icon:5,userCustomType:['AGENT','SELLER','BUYER','CARRIER','STORE']},
        {name:'反馈意见',href:'#feedBack',order:6,icon:7,userCustomType:['AGENT','SELLER','BUYER','CARRIER','STORE']}
    ];
    var localData = {
        userData:{},
        yqhData:{},
        recommendData:[],
        orderData:[],
        sendList:[]
    };

    var initEvent = function () {};
    _.extend(module.PageEventBase.prototype,{
        me:function ($page,pageId,result) {
            if(result.status){
                localData.userData = result.data.info;
            }
            var colMenu =  _.filter(menu,function (o) {
                return _.indexOf(o.userCustomType,localData.userData.userCustomType) >= 0;
            });
            $.loadTemplate($page,{
                userData:localData.userData,
                colMenu:{data:colMenu},
                customersInfo:localData.userData
            },HTML_template);
            $page.find('#logout').on('click',function (e) {
                e.stopPropagation();
                $.logout('/login.html');
            });
        },
        meData:function ($page,pageId,result) {
            // 编辑个人信息
            if(result.status){
                localData.userData = result.data.info;
            }
            var formInputName = _.result(_.find(formKeyName,function (o) {
                return _.indexOf(o.userCustomType,localData.userData.userCustomType) >= 0;
            }),'data');
            console.log(formInputName);
            var userDataEdit =  _.chain(localData.userData).map(function (item,key) {
                var Fkey = _.find(formInputName, function(o,sKey) { return sKey == key; });
                if(Fkey != undefined){
                    return {
                        name:Fkey.name,
                        key:key,
                        val:item,
                        order:Fkey.order
                    };
                }else{
                    return '';
                }

            }).thru(function(value) {
                return _.sortBy(_.compact(value),'order');
            }).value();
            $.loadTemplate($page,{userDataEdit:{data:userDataEdit},userPic:localData.userData},HTML_template)
                .then(function () {
                    $page.find('.fn-meData').click(function () {
                        $(this).addClass('hide');
                        $(this).parents().children('.fn-save').removeClass('hide');
                        $page.find('.meData-box input').removeAttr('disabled');
                    });
                    $page.find('#meDataForm input[name=userCustomType2]').val(localData.userData.userCustomType2);

                    //上传用户头像
                    $page.find('#uploadFile').ajaxfileupload({
                        'action': '/app/imagesUpload.htm',
                        'params':{

                        },
                        'onComplete': function(data) {
                            if(data.code == 1){
                                var picTmp = _.template(HTML_template.userPic);
                                $page.find('#userPic').html(picTmp({userCustomType2:data.serverPath}));
                                $page.find('#meDataForm input[name=userCustomType2]').val(data.serverPath);
                            }else{
                                $.toast(data.message);
                            }
                        },
                        'onStart': function() {
                            console.log('onStart');
                        },
                        'onCancel': function() {
                            console.log('no file selected');
                        }
                    });

                    $page.find("#meDataForm").validate({
                        rules: {
                            storeName : {
                                required:true
                            },
                            address : {
                                required:true
                            },
                            realName : {
                                required:true
                            },
                            mobile:{
                                required: true,
                                phone:true,
                                minlength:11
                            },
                            mobile:{
                                required: true,
                                phone:true,
                                minlength:11
                            },
                            userName:{
                                required:true,
                            }
                        },
                        submitHandler:function(form){
                            $(form).ajaxPostData({},function (data) {
                                $.hidePreloader();
                                if(data.code == 1){
                                    $page.find('.fn-meData').removeClass('hide');
                                    $page.find('.fn-meData').siblings('.fn-save').addClass('hide');
                                    $page.find('.meData-box input').prop('disabled',true);
                                    $.router.back();
                                }else{
                                    $.toast(data.message);
                                    $page.find('.fn-meData').removeClass('hide');
                                    $page.find('.fn-meData').siblings('.fn-save').addClass('hide');
                                    $page.find('.meData-box input').prop('disabled',true);
                                }
                            });
                        }
                    });
                });

        },
        yhq:function ($page,pageId,result) {
            if(result.status){
                localData.yhqData = result.data.list;
            }
            var yhqData = _.chain(localData.yhqData).thru(function (value) {
                return {
                    yhqData1:{
                        data:_.sortBy(_.filter(value,{isUsed:false}),'priceType')
                    },
                    yhqData2:{
                        data:_.sortBy(_.filter(value,{isUsed:true}),'priceType')
                    },
                    yhqCount:_.mapKeys(_.countBy(value,'isUsed'),function (value,key) {
                        return key == 'false'?'type1':'type2'
                    })
                }
            }).value();
            $.loadTemplate($page,yhqData,{yhqData1:HTML_template.yhqData,yhqData2:HTML_template.yhqData,yhqCount:HTML_template.yhqCount});
        },
        changePW2:function ($page,pageId,result){
            $page.find('.eyes').showPass();
            $page.find("#changePWForm").validate({
                rules: {
                    password:{
                        required: true,
                        minlength: 6
                    },
                    newPassword:{
                        required: true,
                        minlength: 6
                    }
                },
                messages:{
                    password:{
                        required:'请填写朋友姓名.'
                    }
                },
                submitHandler:function(form){
                    $(form).ajaxPostData({data:{
                        password:$(form).find("input[name=password]").val(),
                        newPassword:$(form).find("input[name=newPassword]:visible").val(),
                        ex:'ex'
                    }},function (data) {
                        if(data.code == 1){
                            $.alert(data.message, function () {
                                $.router.back();
                                window.location.href = '/login.html?return=' + window.location.href;
                            });

                        }else{
                            $.toast(data.message);
                        }
                    });
                }
            });
        },
        recommend:function ($page,pageId,result){
            $page.find("#recommendForm").validate({
                rules: {
                    tel:{
                        required: true,
                        phone:true,
                        minlength:11
                    },
                    friend:{
                        required:true
                    }
                },
                messages:{
                    friend:{
                        required:'请填写朋友姓名.'
                    }
                },
                submitHandler:function(form){
                    $(form).ajaxPostData({},function (data) {
                        if(data.code == 1){
                            $.alert(data.message, function () {
                                $.router.back();
                            });

                        }else{
                            $.toast(data.message);
                        }
                    });
                }
            });
        },
        feedBack:function ($page,pageId,result){
            $page.find("#feedBackForm").validate({
                submitHandler:function(form){
                    $(form).ajaxPostData({},function (data) {
                        if(data.code == 1){
                            $.alert(data.message, function () {
                                $.router.back();
                            });

                        }else{
                            $.toast(data.message);
                        }
                    });
                }
            });
        },
        recommendCustomers:function ($page,pageId,result) {
            if(result.status){
                localData.recommendData = result.data.list
            }
            $.loadTemplate($page,{
                recommendData:{data:localData.recommendData}
            },HTML_template);
            $page.find('.h-null-btn-nob').on('click',function () {
                if($(this).next().is(':hidden')){
                    $('.shpiaof').fadeOut(400);
                    $(this).next().fadeIn(400);
                }
            });
            $page.find('.close-btn-menu').on('click',function () {
                $(this).parent().fadeOut(400);
            });
            $page.find('.delRecommend').on('click',function () {
                var recommendId = $(this).data('id');
                $.alert('成功删除推荐' + recommendId);
                $(this).parent().fadeOut(400);
            });

        },
        steadOrder:function ($page,pageId,result) {
            if(result.status){
                localData.orderData = result.data.list
            }
            $.loadTemplate($page,{
                orderData:{data:localData.orderData}
            },HTML_template);

        },
        send:function ($page,pageId,result) {
            if(result.status){
                localData.sendList = result.data.list
            }
            $.loadTemplate($page,{
                sendList:{data:localData.sendList}
            },HTML_template);

        }
    });
    var EventList = new module.PageEventBase();
    EventList.setResolve({
        me:{status:true,url:'/app/userInfo.htm',params:{}},
        meData:{status:true,url:'/app/userInfo.htm',params:{}},
        yhq:{status:true,url:'/app/queryGift.htm',params:{}},
        changePW2:{status:false,url:'',params:{}},
        recommend:{status:false,url:'',params:{}},
        feedBack:{status:false,url:'',params:{}},
        recommendCustomers:{status:true,url:'/app/recommendData.htm',params:{}},
        steadOrder:{status:true,url:'/app/steadOrder.htm',params:{}},
        send:{status:true,url:'/app/queryGifted.htm',params:{}}
    });
    var pageId = $('.page.page-current').attr('id');
    EventList.init($('.page.page-current'),pageId);
});